package com.example.springcloudindex.web;

import com.example.springcloudindex.util.JwtUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

// 登录之后 过滤器
@Component
public class LoginedFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        String path = context.getRequest().getServletPath();
        if("/user/login".equals(path)||
                "/spring-cloud-user/login".equals(path)){
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        // 获取上游服务返回的结果
        String body = "";
        // getResponseDataStream 一旦获取的上游的响应数据
        // 那么该数据就会被截留
        InputStream inputStream = context.getResponseDataStream();
        byte[] bytes = new byte[1024];
        try {
            int count = inputStream.read(bytes);
            body = new String(bytes,0,count);
        } catch (IOException e) {
            throw new RuntimeException("error",e);
        }
        if(body.startsWith("登录成功!")){
            // 获取用户信息
            String name = body.substring(body.indexOf("!")+1);
            Map<String,Object> map = new HashMap<>();
            map.put("myname",name);
            String jwt = JwtUtil.createJWT(30, map);
            context.setResponseBody("登录成功!"+ jwt);
        } else {
            // 返回元数据
            context.setResponseBody(body);
        }
        return null;
    }
}
